package com.sinog.alarm.config;

import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;

/**
 * @author wangxj
 * @desc TODO
 * @date 2022/11/23 下午4:32
 */
@Configuration
@MapperScan(basePackages = "com.sinog.alarm.mapper.db1", sqlSessionTemplateRef  = "db1SqlSessionTemplate")
public class DataSource1Config {

    /**
     * db1
     */
    @Autowired
    private DataBase1Properties dataBase1Properties;

    @Bean(name = "db1DataSource")
    //主库加这个注解，修改优先权，表示发现相同类型bean，优先使用该方法。
    @Primary
    public DataSource dbDataSource() {
        HikariDataSource hds = new HikariDataSource();
        hds.setDriverClassName(dataBase1Properties.getDriverClassName());
        hds.setJdbcUrl(dataBase1Properties.getUrl());
        hds.setUsername(dataBase1Properties.getUsername());
        hds.setPassword(dataBase1Properties.getPassword());
        hds.setAutoCommit(true);
        return hds;
    }

    @Bean(name = "db1SqlSessionFactory")
    @Primary
    public SqlSessionFactory dbSqlSessionFactory(@Qualifier("db1DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*xml"));
        //这个的getResources指向的是你的mapper.xml文件，相当于在yml中配置的mapper-locations，此处配置了yml中就不用配置，或者说不会读取yml中的该配置。
        return bean.getObject();
    }

    @Bean(name = "db1TransactionManager")
    @Primary
    public DataSourceTransactionManager dbTransactionManager(@Qualifier("db1DataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "db1SqlSessionTemplate")
    @Primary
    public SqlSessionTemplate dbSqlSessionTemplate(@Qualifier("db1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
